package com.dayaokeji.rhythmschoolstudent.service

import android.app.Service
import android.content.Intent
import android.os.Environment
import android.text.TextUtils
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil
import com.litesuits.common.io.FileUtils
import com.orhanobut.logger.Logger
import com.tencent.bugly.crashreport.CrashReport
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.util.*

// Created by Zeno on 2018/5/25
// version 1.0
// Copyright (C) 2018 -- 2020 ALL Right
class AppUniqueIdService : Service() {

    private val compositeDisposable = CompositeDisposable()

    companion object {
         val APP_PATH = Environment.getExternalStorageDirectory().absolutePath!!
         const val FILE_NAME_SALT = "FYG151293GGsj12sd23jnas23"


        fun getFileString():String? {
            if (PermissionUtil.hasPermission(PermissionGroup.STORE)) {
                val uuidFile = File(APP_PATH, "uuid-$FILE_NAME_SALT")
                if (uuidFile.exists()) {
                    return FileUtils.readFileToString(uuidFile)
                }
            }
            return null
        }
    }

    override fun onBind(intent: Intent?) = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        compositeDisposable.add(Observable.create(ObservableOnSubscribe<String> {
            val randomUUID = UUID.randomUUID().toString()
            it.onNext(randomUUID)
        }).map {
            try {
                if (!TextUtils.isEmpty(it)) {
                    val uuidFile = File(APP_PATH, "uuid-$FILE_NAME_SALT")
                    if (!uuidFile.exists()) {
                        uuidFile.createNewFile()
                    }else{
                        Logger.d("无法创建uuidFile")
                    }
                    if (uuidFile.exists()) {
                        val readFileToString = FileUtils.readFileToString(uuidFile)
                        if (TextUtils.isEmpty(readFileToString)) {
                            FileUtils.write(uuidFile,it)
                        }
                        Logger.d("写入成功之后第二次取出$readFileToString")
                    }
                }else{
                    CrashReport.postCatchedException(IllegalStateException("没有生产UUID"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }.subscribeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread()).subscribe())
        return super.onStartCommand(intent, flags, startId)
    }


    override fun onDestroy() {
        super.onDestroy()
        compositeDisposable.clear()
    }
}